import nvsDataUtils from '@/js/NvsDataUtils'
import ConstDef from '@/js/ConstDef'
import DataSource from '@/js/datasource/DataSource'

class DataSourceUtils {
  getDataSourceConfigs(layout) {
    const configs = [];
    const extensions = nvsDataUtils.getLayoutExtension(layout, ConstDef.LAYOUT_EXTENSION_TYPE_EXTERNAL_DATA_SOURCE);
    for (const extension of extensions) {
      const config = JSON.parse(extension.json);
      configs.push(config);
    }
    return configs;
  }

  getWatchedFdNames (config) {
    const fdNames = [];
    for (const key in config.values) {
      const value = config.values[key];
      if (value.toString().startsWith('@')) { fdNames.push(value.substr(1, value.length - 1)); }
    }
    return fdNames;
  }

  getKVOfNv(nv, fdNames) {
    const kv = {};
    for (const fdName of fdNames) {
      kv[fdName] = nv[fdName];
    }
    return kv;
  }

  explainKeyValues(config, nv) {
    const kv = {}
    for (const key in config.values) {
      const value = config.values[key];
      if (value.toString().startsWith('@')) {
        const fdName = value.substr(1, value.length - 1);
        kv[key] = nv[fdName];
      } else {
        kv[key] = config.values[key];
      }
    }
    return kv;
  }

  async getDataSource(config, nv) {
    if (!nv) return {};
    const kv = this.explainKeyValues(config, nv);
    const ndCode = kv.ndCode;
    const code = kv.code;
    if (!code) return {};
    const codeFdName = kv.codeFdName;
    const dataSourceConfig = { functionName: config.functionName, ndCode, code, codeFdName };
    const dataSource = new DataSource(dataSourceConfig);
    await dataSource.queryData(dataSourceConfig);
    return dataSource;
  }
}

const dataSourceUtils = new DataSourceUtils();
export default dataSourceUtils;
